package com.zbw.printlibrary.printSub;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.Log;
import com.zbw.printlibrary.bean.AttributeBean;
import com.zbw.printlibrary.printConnector.IPrintCallBack;
import com.zbw.printlibrary.printConnector.netWorkInterface;
import com.zbw.printlibrary.util.BitmapUtil;
import com.zbw.printlibrary.util.NetworkPortUtil;
import com.zbw.printlibrary.util.PrintContentToBitmap;
import com.zbw.printlibrary.util.PrintSharedPreferencesUtils;
import com.zbw.printlibrary.util.PrintThreadPoolManager;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import static com.zbw.printlibrary.util.NetworkPortUtil.CutPage;
import static com.zbw.printlibrary.util.NetworkPortUtil.fontSizeSetBig;
import static com.zbw.printlibrary.util.NetworkPortUtil.setBold;
import static com.zbw.printlibrary.util.NetworkPortUtil.setLocation;

/**
 * 作者 ：Wesley
 * 时间 ：2019-12-19 16:53
 * 这个类是干嘛的？：PrintNetworkPort
 * 网口打印机
 */
public class PrintNetworkPort implements netWorkInterface {
    private Context mContext;
    private IPrintCallBack mCallBack;
    //private Socket client;
    private boolean IFOpen;
    private String ip;
    private String Port;

    private Boolean buzzerIsOpen = false;//是否开启蜂鸣
    private int buzzerNumber;//蜂鸣次数
    private int buzzerTime;//持续时间


    public PrintNetworkPort(Context context, IPrintCallBack callBack) {
        mContext = context;
        mCallBack = callBack;
    }

    @Override
    public void connectPrinter() {
        ip= PrintSharedPreferencesUtils.getParam(mContext,"editTextIps","");
        Port= PrintSharedPreferencesUtils.getParam(mContext,"editTextPorts","");
    }

    //设置ip和端口号
    @Override
    public void setIpAndPort(String ip,String port){
        this.ip = ip;
        this.Port = port;
    }

    /**
     * 设置是否蜂鸣
     * @param isOpen 是否开启蜂鸣
     * @param number 次数
     * @param time 时间
     */
    @Override
    public void setDefaultBuzzer(Boolean isOpen, int number, int time) {
        buzzerIsOpen = isOpen;
        buzzerNumber = number;
        buzzerTime = time;
    }

    private void setBuzzer(Socket client){
        if(buzzerIsOpen){
            //蜂鸣器
            NetworkPortUtil.defaultBuzzer(client,buzzerNumber,buzzerTime);
        }
    }

    @Override
    public void disConnectPrinter() {

    }

    @Override
    public void printTest(List<String> testList) {
        if("".equals(ip)||"".equals(Port)){
            mCallBack.onPrintResult(false);
            Log.e("网口连接错误","IP地址、端口号不能为空");
            return;
        }
        //打印
        if(testList!=null&&testList.size()>2){
            printText(testList);
        }else{
            Log.e("网口打印错误","打印集合不能为空，并且长度不能小于2");
            mCallBack.onPrintResult(false);
        }
    }

    @Override
    public void printString(final List<AttributeBean> testList) {
        //开始打印
        PrintThreadPoolManager.getInstance().executeTask(new Runnable() {
            @Override
            public void run() {
                mCallBack.onDisConnect( "开始打印",true);
                Socket client = null;
                try {
                    Thread.sleep(800);
                    client = new Socket();
                    Log.i("--printText--","ip="+ip+"port="+Port);
                    InetSocketAddress isa = new InetSocketAddress(ip, Integer.parseInt(Port));//打印设备端口号  一般为9100
                    client.connect(isa, 1000);//设置网络超时时间
                    IFOpen = true;
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.e("网口连接错误",e.getMessage());
                    mCallBack.onDisConnect(e.getMessage() + "第123 行",true);
                    IFOpen = false;
                }
                //如果连接失败，等2秒再重试
                if(!IFOpen){
                    try {
                        mCallBack.onDisConnect( "第一次连接失败，等2秒，开始第二次连接打印机 第129 行",true);
                        Thread.sleep(2000);
                        client = new Socket();
                        Log.i("--printText--","ip="+ip+"port="+Port);
                        InetSocketAddress isa = new InetSocketAddress(ip, Integer.parseInt(Port));//打印设备端口号  一般为9100
                        client.connect(isa, 5000);//设置网络超时时间
                        IFOpen = true;
                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.e("网口连接错误",e.getMessage());
                        mCallBack.onDisConnect(e.getMessage() + "第138 行",true);
                        IFOpen = false;
                    }
                }


                if (!IFOpen) {//这么加判断的原因是因为有的打印机有记忆功能，打印机因为没有打开，
                    // 导致异常，再次打开时会接着打印，关闭这种功能
                    mCallBack.onPrintResult(false);
                    return;
                }
                try {
                    //打印输出   控制输出字符集位GBK  否则中文乱码
                    PrintWriter oStream = new PrintWriter((new OutputStreamWriter(client.getOutputStream(), "GBK")), true);
                    for (int i = 0; i < testList.size(); i++) {
                        if (1 == testList.get(i).getContext_type()){//图片
                            //设置居中
                            setLocation(oStream,testList.get(i).getFont_gray());
                            client.getOutputStream().write(BitmapUtil.genBitmapCode(testList.get(i).getBitmap()));
                        }else {
                            //设置居中
                            setLocation(oStream,testList.get(i).getFont_gray());
                            //设置副标题字体大小
                            fontSizeSetBig(oStream,testList.get(i).getFont_size());
                            if (testList.get(i).getFont_size()!=0){
                                //设置字体加粗
                                setBold(oStream,true);
                            }else{
                                //取消字体加粗
                                setBold(oStream,false);
                            }
                            oStream.println(testList.get(i).getContext());
                        }
                    }
                    mCallBack.onDisConnect( "详情信息组装完成",true);
                    setLocation(oStream,0);
                    fontSizeSetBig(oStream,0);
                    oStream.println();
                    //切纸
                    CutPage(client, 1);
                    //蜂鸣器
                    setBuzzer(client);
                    oStream.close();
                    client.close();
                    //closeBitmap(testList);
                } catch (Exception e) {
                    mCallBack.onDisConnect(e.getMessage() + "第165 行",true);
                    e.printStackTrace();
                    mCallBack.onPrintResult(false);
                }
            }
        });
    }

    /**
     * 主动释放图片资源
     * @param testList
     */
    private void closeBitmap(List<AttributeBean> testList){
        for (int i = 0; i < testList.size(); i++) {
            if(testList.get(i).getBitmap() != null){
                try{
                    testList.get(i).getBitmap().recycle();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 打印文本
     * @param liststr
     */
    private void printText(final List<String> liststr){
        //开始打印
        PrintThreadPoolManager.getInstance().executeTask(new Runnable() {
            @Override
            public void run() {
                Socket client = null;
                try {
                    Thread.sleep(800);
                    client = new Socket();
                    Log.i("--printText--","ip="+ip+"port="+Port);
                    InetSocketAddress isa = new InetSocketAddress(ip, Integer.parseInt(Port));//打印设备端口号  一般为9100
                    client.connect(isa, 1000);//设置网络超时时间
                    IFOpen = true;
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.e("网口连接错误",e.getMessage());
                    IFOpen = false;
                }

                if (!IFOpen) {//这么加判断的原因是因为有的打印机有记忆功能，打印机因为没有打开，
                    // 导致异常，再次打开时会接着打印，关闭这种功能
                    mCallBack.onPrintResult(false);
                    return;
                }
                try {
                    //打印输出   控制输出字符集位GBK  否则中文乱码
                    PrintWriter oStream = new PrintWriter((new OutputStreamWriter(client.getOutputStream(), "GBK")), true);
                    //设置居中
                    setLocation(oStream,1);
                    //设置字体加粗
                    setBold(oStream,true);
                    //设置主标题字体大小
                    fontSizeSetBig(oStream,2);
                    oStream.println(liststr.get(0));
                    //设置副标题字体大小
                    fontSizeSetBig(oStream,1);
                    oStream.println(liststr.get(1));
                    //取消字体加粗
                    setBold(oStream,false);
                    //字体右对齐
                    setLocation(oStream,0);
                    for (int i = 2; i < liststr.size(); i++) {
                        oStream.println(liststr.get(i));
                    }
                    //蜂鸣器
                    setBuzzer(client);
                    //切纸
                    CutPage(client, 2);
                    oStream.close();
                    client.close();
                } catch (Exception e) {
                    e.printStackTrace();
                    mCallBack.onPrintResult(false);
                }
            }
        });
    }

    @Override
    public void printStringAndBitmap(List<String> testList, final LinkedHashMap<Integer,Bitmap> bitmapHashMap) {
        printTest(testList);
    }

    @Override
    public void blueConnect(String address) {

    }

    @Override
    public void disBlueConnect() {

    }

    @Override
    public void openMoneyBox() {
        PrintThreadPoolManager.getInstance().executeTask(new Runnable() {
            @Override
            public void run() {
                Log.i("--openMoneyBox--", "ip=" + ip + "port=" + Port);
                try {
                    Thread.sleep(800);
                    if("".equals(ip)||"".equals(Port)) {
                        Log.e("开钱箱错误","ip和端口号不能为空");
                    }else{
                        Socket client = new Socket();
                        Log.i("--printText--", "ip=" + ip + "port=" + Port);
                        InetSocketAddress isa = new InetSocketAddress(ip, Integer.parseInt(Port));//打印设备端口号  一般为9100
                        client.connect(isa, 1000);//设置网络超时时间
                        OutputStream stream = client.getOutputStream();
                        byte[] bits = new byte[]{27, 112, 0, 64, 80};
                        stream.write(bits);
                        stream.close();
                        client.close();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    Log.e("开钱箱错误",e.getMessage());
                }
            }
        });
    }

    @Override
    public boolean isConnected() {
        return false;
    }


    @Override
    public void printString(List<AttributeBean> testList, int width) {
        List<List<AttributeBean>> allData = new ArrayList<>();
        List<AttributeBean> temList = null;
        for (int i = 0; i < testList.size(); i++) {
            if(temList == null){
                temList = new ArrayList<>();
            }
            temList.add(testList.get(i));
            if(testList.get(i).isFont_line()){
                allData.add(temList);
                temList = null;
            }
        }
        List<AttributeBean> data = new ArrayList<>();
        for (int i = 0; i < allData.size(); i++) {
            PrintContentToBitmap bt = new PrintContentToBitmap(allData.get(i),width);
            try {
                Bitmap bitmap = bt.Print();
                data.add(new AttributeBean(0,0,"",1,bitmap));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        printString(data);
    }

}
